//
//  CYCityChooseView.m
//  阿帕
//
//  Created by mac on 2019/12/30.
//  Copyright © 2019 GCY. All rights reserved.
//

#import "CYCityChooseView.h"

@interface CYCityChooseView ()<UIPickerViewDelegate,UIPickerViewDataSource>
{
    NSString *_provinceCode;
    NSString *_provinceName;
    
    NSString *_cityCode;
    NSString *_cityName;
    
    NSString *_countyCode;
    NSString *_countyName;
    
    
    NSString *_regionCode;
    NSString *_regionName;
    
    NSInteger _provinceIndex;
}
@property (nonatomic,strong)UIPickerView *pickerView;

@property (nonatomic,strong)UIView *barrierView;

@property (nonatomic, strong) NSMutableArray *bigSouce;

@property (nonatomic, assign) BOOL isReset;

@end

@implementation CYCityChooseView

+ (CYCityChooseView *)shared {
    
    static dispatch_once_t predicate;
    
    static CYCityChooseView *objc;
    
    dispatch_once(&predicate, ^{
        
        objc = [[CYCityChooseView alloc] init];
        
    });
    
    return objc;
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        
        self.frame = CGRectMake(0, 0, ScreenW, ScreenH);
        
        [self setUpUI];
    }
    
    return self;
}

- (void)hidden {
    
    self.hidden = YES;
    _isReset = NO;
}

- (void)show {
    
    self.hidden = NO;
    if (_isReset) {
        [self dataFirstTimeLoad];
    }
}

- (void)setUpUI {
    
    _provinceCode = @"";
    _provinceName = @"";
    _cityCode = @"";
    _cityName = @"";
    _countyCode = @"";
    _countyName = @"";
    _regionCode = @"";
    _regionName = @"";
    _provinceIndex = 0;
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0.5];
    
    UIView *pickerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH-kP6(220), ScreenW, kP6(220))];
    pickerBgView.tag = 500;
    pickerBgView.backgroundColor = [UIColor whiteColor];
    [self addSubview:pickerBgView];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(kP6(10), kP6(39), ScreenW-kP6(20), kP6(1))];
    line.backgroundColor = BackgroundColor;
    [pickerBgView addSubview:line];
    
    NSArray *pickerTitles = @[@"取消", @"重置", @"确定"];
    for (int i=0; i<pickerTitles.count; i++) {
        UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        cancelBtn.tag = 200 + i;
        [cancelBtn setTitle:pickerTitles[i] forState:UIControlStateNormal];
        cancelBtn.titleLabel.font = font(15);
        [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        cancelBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [DCSpeedy dc_chageControlCircularWith:cancelBtn AndSetCornerRadius:5 SetBorderWidth:0 SetBorderColor:nil canMasksToBounds:YES];
        
        if (i==0) {
            cancelBtn.frame = CGRectMake(kP6(10), kP6(5), kP6(60), kP6(30));
            [cancelBtn setBackgroundColor:Light_TextColor];
        } else if (i==1) {
            cancelBtn.frame = CGRectMake(ScreenW-kP6(140), kP6(5), kP6(60), kP6(30));
            [cancelBtn setBackgroundColor:Red_TextColor];
        } else {
            cancelBtn.frame = CGRectMake(ScreenW-kP6(70), kP6(5), kP6(60), kP6(30));
            [cancelBtn setBackgroundColor:Theme_ColorValue];
        }
        [cancelBtn addTarget:self action:@selector(btnTypeClick:) forControlEvents:UIControlEventTouchUpInside];
        [pickerBgView addSubview:cancelBtn];
    }
    
    [self localStoreRegionSelectorAllData];
}

- (void)setPageShowFlag:(NSInteger)pageShowFlag {
    _pageShowFlag = pageShowFlag;
    
    UIButton *resetBtn = [self viewWithTag:201];
    
    if (pageShowFlag == 1) {
        UIView *pickerBgView = [self viewWithTag:500];
        pickerBgView.frame = CGRectMake(0, ScreenH-kP6(220), ScreenW, kP6(220));
        
        resetBtn.hidden = YES;
        
    } else {
        resetBtn.hidden = NO;
    }
}

- (void)btnTypeClick:(UIButton *)sender {
    
    if ([sender.titleLabel.text isEqual:@"确定"]) {
        //确定
        if (self.delegate && [self.delegate respondsToSelector:@selector(getAllInfoProvinceCode:provinceName:cityCode:cityName:countyCode:countyName:)]) {
            if ([DCSpeedy isBlankString:_cityCode] == YES) {
                _cityName = @"";
            }
            if ([DCSpeedy isBlankString:_countyCode] == YES) {
                _countyName = @"";
            }
            
//            if ([_cityName isEqualToString:_provinceName]) {
//                _provinceCode = @"";
//                _provinceName = @"";
//            }
            
            [self.delegate getAllInfoProvinceCode:_provinceCode provinceName:_provinceName cityCode:_cityCode cityName:_cityName countyCode:_countyCode countyName:_countyName];
        }
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(getChooseRegionCode:andRegionName:)]) {
            [self.delegate getChooseRegionCode:_regionCode andRegionName:_regionName];
        }
        
        [self hidden];
        
    } else if ([sender.titleLabel.text isEqual:@"重置"]) {
        //重置操作
        [self hidden];
        
        _isReset = YES;
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(getAllInfoProvinceCode:provinceName:cityCode:cityName:countyCode:countyName:)]) {
            [self.delegate getAllInfoProvinceCode:@"" provinceName:@"重置" cityCode:@"" cityName:@"" countyCode:@"" countyName:@""];
        }
        
        _provinceIndex = 0;
        [self.pickerView selectRow:0 inComponent:0 animated:YES];
        [self.pickerView selectRow:0 inComponent:1 animated:YES];
        [self.pickerView selectRow:0 inComponent:2 animated:YES];
        [self.pickerView reloadAllComponents];
        
        _provinceCode = @"";
        _provinceName = @"重置";
        _cityName = @"";
        _cityCode = @"";
        _countyName = @"";
        _countyCode = @"";
        _regionName = @"";
        _regionCode = @"";
        
    } else if ([sender.titleLabel.text isEqual:@"取消"]) {
        
        [self hidden];
    }
}

#pragma mark - UIPickerViewDataSouce
// Components
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return _isTwoLevel ? 2 : 3;
}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 40;
}
//Rows
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    //    某一列当前选中的行号 selectedRowInComponent
    if (component == 0) {
        return self.bigSouce.count;
    } else if (component == 1) {
        ArpaProvinceModel *pModel = self.bigSouce[_provinceIndex];
        return pModel.children.count;
    } else {
        ArpaProvinceModel *pModel = self.bigSouce[_provinceIndex];
        NSInteger cityIndex = [pickerView selectedRowInComponent:1];
        ArpaCityModel *cModel = pModel.children[cityIndex];
        return cModel.children.count;
    }
}
//title
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    if (0 == component) {
        ArpaProvinceModel *provinceModel = [self.bigSouce objectAtIndex:row];
        return provinceModel.countyName;
    }
    else if (1 == component) {
        ArpaProvinceModel *provinceModel = self.bigSouce[_provinceIndex];
        ArpaCityModel *cityModel = provinceModel.children[row];
        return cityModel.countyName;
    } else {
        ArpaProvinceModel *provinceModel = self.bigSouce[_provinceIndex];
        NSInteger cityIndex = [pickerView selectedRowInComponent:1];
        ArpaCityModel *cityModel = provinceModel.children[cityIndex];
        ArpaCountyModel *countyModel = [cityModel.children objectAtIndex:row];
        return countyModel.countyName;
    }
    
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setTextColor:Dark_TextColor];
        [pickerLabel setFont:font(15)];
    }
    // Fill the label text here
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

//Select
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    if (component == 0) { // 滚动省会,刷新城市（1列）
        // 记录当前选中的省会
        _provinceIndex = [pickerView selectedRowInComponent:0];
        
        [pickerView selectRow:0 inComponent:1 animated:YES];
        [pickerView selectRow:0 inComponent:2 animated:YES];
        [pickerView reloadAllComponents];
    }
    
    if (component == 1) {
        [pickerView selectRow:0 inComponent:2 animated:YES];
        [pickerView reloadAllComponents];
    }
    
    // 获取选中省会
    ArpaProvinceModel *province = self.bigSouce[_provinceIndex];
    
    NSLog(@"省-- %@,province_id-- %@ ",province.countyName,province.countyCode);
    
    NSInteger cityIndex = [pickerView selectedRowInComponent:1];
    
    NSLog(@" cityIndex %ld ",cityIndex);
    
    ArpaCityModel *cityModel = province.children[cityIndex];
    
    NSLog(@"city_id---%@ cityName--- %@ ", cityModel.countyCode, cityModel.countyName);
    
    _provinceCode = province.countyCode;
    _provinceName = province.countyName;
    _cityName = cityModel.countyName;
    _cityCode = cityModel.countyCode;
    
    if (!_isTwoLevel) {
        NSInteger areaIndex = [pickerView selectedRowInComponent:2];
        
        NSLog(@" areaIndex %ld ",areaIndex);
        
        ArpaCountyModel *countyModel = cityModel.children[areaIndex];
        
        NSLog(@"区ID---%@ 区---%@ ",countyModel.countyCode, countyModel.countyName);
        _countyName = countyModel.countyName;
        _countyCode = countyModel.countyCode;
        _regionName = countyModel.countyName;
        _regionCode = countyModel.countyCode;
    }
    
}

- (UIPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, kP6(40), ScreenW, kP6(180))];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        _pickerView.backgroundColor = [UIColor whiteColor];
        _pickerView.showsSelectionIndicator = YES;
    }
    return _pickerView;
}
- (UIView *)barrierView {
    if (!_barrierView) {
        //黑色遮挡层
        _barrierView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH)];
        _barrierView.backgroundColor = RGBA(0, 0, 0, 0.5);
        //        _barrierView.hidden = YES;
    }
    return _barrierView;
}
- (NSMutableArray *)bigSouce {
    if (!_bigSouce) {
        _bigSouce = [[NSMutableArray alloc] init];
    }
    return _bigSouce;
}

- (void)localStoreRegionSelectorAllData {
    WEAKSELF
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"RegionSelectorData"];
    
    if ([fileManager fileExistsAtPath:filePath] == NO) {
        //本地不存在plist
        //拉取全部省市区数据
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/areaProvince/queryList", [ReAddressDynamic shared].baseUrl) withParameter:nil withVC:nil netName:@"省市区列表" success:^(id response, NSString *msg) {
            
            if ([DCSpeedy isBlankArr:response[@"records"]] == NO) {
                
                [weakSelf.bigSouce addObjectsFromArray:[ArpaProvinceModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
                
                UIView *pbView = [weakSelf viewWithTag:500];
                [pbView addSubview:weakSelf.pickerView];
                
                [weakSelf.pickerView reloadAllComponents];
                
                [weakSelf.bigSouce writeToFile:filePath atomically:YES];
                
                [self dataFirstTimeLoad];
                
            } else {
                
                [XSInfoView showInfo:@"省市区列表暂无数据" onView:self.window];
            }
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
    } else {
        
        //读取数据
        BOOL bRet = [fileManager fileExistsAtPath:filePath];
        if (bRet) {
            NSMutableArray *dataArray = [NSMutableArray arrayWithContentsOfFile:filePath];
            self.bigSouce = dataArray;
            DebugLog(@"最终数据 = %@", dataArray);
        }
    }
    
}

#pragma mark - 首次加载数据赋值
- (void)dataFirstTimeLoad {
    
    ArpaProvinceModel *province = self.bigSouce[_provinceIndex];
    
    NSInteger cityIndex = [self.pickerView selectedRowInComponent:1];
    
    ArpaCityModel *cityModel = province.children[cityIndex];
    
    _provinceCode = province.countyCode;
    _provinceName = province.countyName;
    _cityName = cityModel.countyName;
    _cityCode = cityModel.countyCode;
    
    if (!_isTwoLevel) {
        NSInteger areaIndex = [self.pickerView selectedRowInComponent:2];
        ArpaCountyModel *countyModel = cityModel.children[areaIndex];
        _countyName = countyModel.countyName;
        _countyCode = countyModel.countyCode;
        _regionName = countyModel.countyName;
        _regionCode = countyModel.countyCode;
    }
}

@end
